package com.zygh.lz.controller.pc;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.entity.IntegrationPlatform;
import com.zygh.lz.entity.bean.Video;
import com.zygh.lz.service.EquipageTypeService;
import com.zygh.lz.service.impl.IntegrationPlatformService;
import com.zygh.lz.stapprove.*;
import com.zygh.lz.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

@Api(tags = "融合音视频平台")
@Slf4j
@RestController
public class EquipageController {

    @Resource
    private IntegrationPlatformService integrationPlatformService;


    @Value("${tcp.enable:true}")
    private boolean enable;

//    @Value("${tcp.ip:62.66.3.59}")
//    private String ip;

    @Value("${tcp.port:11001}")
    private int port;

    @ApiOperation("获取ip")
    @GetMapping("getIp")
    public String getIp() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 客户端ip
        return SysLogAspect.getRemoteIP(request);
    }

    @ApiOperation("发送指令")
    @GetMapping("sendEquipage")
    public void sendEquipage(String ip, String gpsid) {
        String ips = getIp();
        Video video = new Video();
        String[] strings = new String[]{gpsid};
        video.setVideoCallNums(strings);
        video.setAudioCallNums(strings);
        log.info("ip:" + ip);
        log.info("ips:" + ips);
        log.info("端口:" + this.port);
        log.info("入参:" + JSON.toJSONString(video));
        //TCP发送数据
        //JSONObject.parseObject(id).get("id").toString();
        sendAndReceive(ips, this.port, JSON.toJSONString(video));

    }

    private static void sendAndReceive(String ip, int port, String msg) {
        //这里比较重要，需要给请求信息添加终止符，否则服务端会在解析数据时，一直等待
        //开启一个链接，需要指定地址和端口
        //写
        OutputStream out;
        //客户机
        Socket socket = new Socket();
        try {
            socket.setTcpNoDelay(true);
            socket.setReuseAddress(true);
            socket.setSoTimeout(30000);
            socket.setSoLinger(true, 5);
            socket.setSendBufferSize(1024);
            socket.setReceiveBufferSize(1024);
            socket.setKeepAlive(true);
            socket.connect(new InetSocketAddress(ip, port), 30000);
            //向输出流中写入数据，传向服务端
            out = socket.getOutputStream();
            out.write(msg.getBytes());
            socket.close();
        } catch (Exception e) {
            log.error("TCP连接失败：", e);
            e.printStackTrace();
        }
    }

    @ApiOperation("监听TCP端口")
    @GetMapping("monitor")
    public ResultBean monitor(String ip) {
        //1、TCP 服务接收IP为：融合通讯平台所在PC电脑上的本地IP地址。
        ip = getIp();
        //客户机
        Socket socket = new Socket();
        try {
            socket.setTcpNoDelay(true);
            socket.setReuseAddress(true);
            socket.setSoTimeout(30000);
            socket.setSoLinger(true, 5);
            socket.setSendBufferSize(1024);
            socket.setReceiveBufferSize(1024);
            socket.setKeepAlive(true);
            socket.connect(new InetSocketAddress(ip, this.port), 30000);
            //向输出流中写入数据，传向服务端
            socket.close();
            return ResultUtil.setOK("success", null);
        } catch (Exception e) {
            log.error(ip + "TCP连接失败：", e);
            e.printStackTrace();
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    @ApiOperation("查询所有")
    @GetMapping("findPlatformAll")
    public ResultBean findPlatformAll() {

        return ResultUtil.setOK("success", integrationPlatformService.list());

    }

    @ApiOperation("根据账号查询")
    @GetMapping("getPlatform")
    public ResultBean getPlatform(String user) {
        return ResultUtil.setOK("success", integrationPlatformService.getPlatform(user));

    }


    @ApiOperation("新增插入")
    @PostMapping("insertPlatform")
    //@SysPcLog(module = "新增融合平台账号",operation = "新增")
    public ResultBean insert(@RequestBody IntegrationPlatform integrationPlatform) {
        integrationPlatform.setCreatTime(DateUtil.now());
        return ResultUtil.execOp(integrationPlatformService.insert(integrationPlatform), "添加");

    }


    @ApiOperation("修改")
    @PostMapping("updatePlatform")
    //@SysPcLog(module = "修改融合平台账号",operation = "修改")
    public ResultBean update(IntegrationPlatform integrationPlatform) {
        return ResultUtil.execOp(integrationPlatformService.update(integrationPlatform), "修改");
    }


    @ApiOperation("删除")
    @PostMapping("deletePlatform")
    //@SysPcLog(module = "删除融合平台账号",operation = "删除")
    public ResultBean delete(@RequestBody String id) {
        String str = JSONObject.parseObject(id).get("id").toString();
        Integer new_id = Integer.parseInt(str);
        return ResultUtil.execOp(integrationPlatformService.delete(new_id), "删除");
    }

}

